package com.nsi.service.Impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nsi.common.Const;
import com.nsi.common.ServerResponse;
import com.nsi.dao.ActivityMapper;
import com.nsi.dao.EntryAuditMapper;
import com.nsi.dao.LogMapper;
import com.nsi.dao.Vis2019Mapper;
import com.nsi.pojo.*;
import com.nsi.service.ElectronicTicketService;
import com.nsi.service.EntryAuditService;
import com.nsi.service.EventCollectService;
import com.nsi.service.IActivityService;
import com.nsi.util.*;
import com.nsi.vo.ActiveOrderVo;
import com.nsi.vo.ActiveReviewVo;
import com.nsi.vo.EventOrderVo;
import com.wechat.pay.PayUtil;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.schema.Server;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.awt.image.BufferedImage;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Luo Zhen
 */
@Service
@Slf4j
public class ActivityServiceImpl implements IActivityService {

    @Autowired
    private ActivityMapper activityMapper;
    @Autowired
    private LogMapper logMapper;
    @Autowired
    private Vis2019Mapper vis2019Mapper;
    @Autowired
    private EntryAuditService entryAuditService;
    @Autowired
    private EntryAuditMapper entryAuditMapper;
    @Autowired
    private ElectronicTicketService electronicTicketService;
    @Autowired
    private EventCollectService eventCollectService;


    /**
     * 返回图片地址
     *
     * @param nickName
     * @param mark
     * @return
     */
    @Override
    public ServerResponse resultImageUrl(String nickName, Integer mark) {
        if (StringUtils.isBlank(nickName) || mark == null) {
            return ServerResponse.createByErrorMessage("参数不合法");
        }
        //生成一个4伪随机数图片的名字
        String fileName = new StringBuffer().append(PayUtil.getRandomString(10)).append(".jpg").toString();
        //判断分数，返回对应的分数图片
        String url = null;
        if (mark >= 100) {
            url = this.validStrLength(nickName, fileName, Const.imageUrl.image_one);
        } else if (mark >= 80 && mark < 100) {
            url = this.validStrLength(nickName, fileName, Const.imageUrl.image_two);
        } else if (mark >= 60 && mark < 80) {
            url = this.validStrLength(nickName, fileName, Const.imageUrl.image_three);
        } else if (mark >= 40 && mark < 60) {
            url = this.validStrLength(nickName, fileName, Const.imageUrl.image_four);
        } else if (mark >= 20 && mark < 40) {
            url = this.validStrLength(nickName, fileName, Const.imageUrl.image_five);
        } else {
            url = this.validStrLength(nickName, fileName, Const.imageUrl.image_six);
        }
        return ServerResponse.createBySuccess(url);
    }

    /**
     * 返回合成图片的地址
     *
     * @param imageUrl
     * @return
     */
    @Override
    public ServerResponse getTicketImageUrl(String imageUrl) {
        if (StringUtils.isBlank(imageUrl)) {
            return ServerResponse.createByErrorMessage("参数不合法");
        }
        //下载的文件名字s
        String fileName = RandomStringUtils.randomNumeric(8) + ".jpg";
        //下载图片地址
        try {
            ImageUtil.download(imageUrl, fileName, PropertiesUtil.getProperty("image.file.url"));
        } catch (Exception e) {
            log.info("图片下载到本地失败！");
            e.printStackTrace();
        }

        //获取二维码图片路径
        String qrImageUrl = PropertiesUtil.getProperty("image.file.url") + fileName;
        log.info("二维码图片路径:{}", qrImageUrl);

        //获取被合成的大图路径
        String bigImageUrl = Const.imageUrl.TICKET_IMAGE_VIS2019_ZX;
        log.info("大图路径:{}", bigImageUrl);

        this.compositePicture(bigImageUrl, qrImageUrl, 190, 460, fileName);


        //返回图片地址
        String url = PropertiesUtil.getProperty("ticket.file.url") + fileName;

        return ServerResponse.createBySuccess(url);
    }

    /**
     * 图片合成
     *
     * @param fileName    文件名字
     * @param qrImageUrl  二维码图片地址
     * @param bigImageUrl 大图图片地址
     * @param x           图片x坐标
     * @param y           图片y坐标
     */
    private String compositePicture(String bigImageUrl, String qrImageUrl, int x, int y, String fileName) {
        //实例化工具类
        ImageUtil tt = new ImageUtil();
        //嵌套的二维码
        BufferedImage d = tt.loadImageLocal(qrImageUrl);
        //读取大图
        BufferedImage b = tt.loadImageLocal(bigImageUrl);

        //生成图片位置
        String ticketImageUrl = PropertiesUtil.getProperty("compound.file.url") + fileName;
        log.info("生成图片路径:{}", ticketImageUrl);
        //合并图片
        tt.writeImageLocal(ticketImageUrl, tt.modifyImagetogeter(d, b, x, y));
        return ticketImageUrl;
    }

    /**
     * 文字合成图片
     *
     * @param qrImgUrl
     * @param username
     * @return
     */
    @Override
    public ServerResponse getVISImgUrl(String qrImgUrl, String username, String type) {
        if (StringUtils.isBlank(qrImgUrl) || StringUtils.isBlank(username)) {
            return ServerResponse.createByErrorMessage("参数不合法");
        }
        String bigImgUrl = null;
        if (type.equals("zx")) {
            bigImgUrl = Const.imageUrl.TICKET_IMAGE_VIS2019_ZX;
        } else {
            bigImgUrl = Const.imageUrl.TICKET_IMAGE_VIS2019_GB;
        }
        // 随机图片名字
        String fileName = RandomStringUtils.randomNumeric(8) + ".jpg";
        // 下载二维码图片地址
        String fileImgUrl = null;
        try {
            ImageUtil.download(qrImgUrl, fileName, PropertiesUtil.getProperty("image.file.url"));
            fileImgUrl = PropertiesUtil.getProperty("image.file.url") + fileName;
        } catch (Exception e) {
            log.info("【图片合成功能】,图片下载到本地失败！");
            e.printStackTrace();
        }
        // 第一次合成文字
        String fileUrl = this.compositePicture(bigImgUrl, fileImgUrl, 235, 490, fileName);
        System.out.println("fileUrl:" + fileUrl);

        int x = 0;
        if (this.isChinese(username)) {
            x = -(50 * username.length() / 2);
        } else {
            x = -(23 * username.length() / 2);
        }

        // 第二次合成图片
        String visImageUrl = getImageUrl(fileUrl, username, x, 300, fileName);
        // 拼接线上地址
        visImageUrl = PropertiesUtil.getProperty("localhost.file.url") + fileName;
        return ServerResponse.createBySuccess(visImageUrl);
    }

    /**
     * 判断该字符串是否是英文还是中文
     *
     * @param str
     * @return
     */
    public boolean isChinese(String str) {
        if (str == null) {
            return false;
        }
        for (char c : str.toCharArray()) {
            // 如果是中文
            if (isChinese(c)) {
                return true;
            }
        }
        return false;
    }

    public boolean isChinese(char c) {
        return c >= 0x4E00 && c <= 0x9FA5;
    }

    /**
     * 合成图片方法
     * DD
     *
     * @param imageUrl 大图地址
     * @param referrer 合成文字
     * @param x        文字位置 x轴
     * @param y        文字位置 y轴
     * @param fileName 文件名字
     * @return
     */
    private String getImageUrl(String imageUrl, String referrer, int x, int y, String fileName) {
        ImageUtil imageUtil = new ImageUtil();
        BufferedImage bufferedImage = imageUtil.loadImageLocal(imageUrl);
        imageUtil.modifyImage(bufferedImage, referrer, x, y);
        String url = PropertiesUtil.getProperty("generate.image.url") + fileName;
        imageUtil.writeImageLocal(url, bufferedImage);
        return url;
    }

    /**
     * 添加活动
     *
     * @param activity
     * @return
     */
    @Override
    public ServerResponse saveon(Activity activity) {
        if (StringUtils.isBlank(activity.getContent1()) || StringUtils.isBlank(activity.getContent2())) {
            return ServerResponse.createByErrorMessage("参数不合法");
        }
        activity.setLoadTime(DateTimeUtil.dateToStr(new Date()));
        int rowCount = activityMapper.insert(activity);
        if (rowCount > 0) {
            return ServerResponse.createBySuccessMessage("添加活动信息成功");
        }
        return ServerResponse.createByErrorMessage("添加活动信息失败");
    }

    /**
     * 查询活动列表功能
     *
     * @return
     */
    @Override
    public ServerResponse searchList() {
        List<Activity> activityList = activityMapper.getActivityList();
        return ServerResponse.createBySuccess(activityList);
    }

    @Override
    public Activity findOne(Integer activityId) {
        return activityMapper.selectByPrimaryKey(activityId);
    }

    /**
     * 查询信息列表功能
     *
     * @param title1
     * @return
     */
    @Override
    public ServerResponse searchInfo(String title1) {
        if (StringUtils.isBlank(title1)) {
            return ServerResponse.createByErrorMessage("参数不合法");
        }
        List<Activity> activityList = activityMapper.selectByTitleAndContent(title1);
        return ServerResponse.createBySuccess(activityList);
    }

    /**
     * 公共方法
     *
     * @param nickName
     * @param fileName
     * @param imageUrl
     * @return 图片地址
     */
    private String getString(String nickName, String fileName, String imageUrl, int x, int y) {
        //读取图片
        ImageUtil imageUtil = new ImageUtil();
        BufferedImage bufferedImage = imageUtil.loadImageLocal(imageUrl);
        //修改名字在图片的位置
        imageUtil.modifyImage(bufferedImage, nickName, x, y);
        String url = PropertiesUtil.getProperty("generate.image.url") + fileName;
        log.info("写出文件的位置:{}", url);
        imageUtil.writeImageLocal(url, bufferedImage);
        url = PropertiesUtil.getProperty("localhost.file.url") + fileName;
        log.info("返回前段文件的位置:{}", url);
        return url;
    }

    /**
     * 验证名字的长度改变不同尺寸
     *
     * @param nickName
     * @param fileName
     * @param imageUrl
     * @return
     */
    private String validStrLength(String nickName, String fileName, String imageUrl) {
        String url;
        if (nickName.length() > 3) {
            url = this.getString(nickName, fileName, imageUrl, -153, 95);
        } else {
            url = this.getString(nickName, fileName, imageUrl, -113, 95);
        }
        return url;
    }

//    错误逻辑 ！！！！！！！！！！！！！！！！！！！！！

    @Override
    public ServerResponse modifyUserInfo(String usermail, String classId) {
        log.info("------------------------>进入到修改活动业务接口");
        log.info("------->userMail:{}", usermail);
        log.info("------->classId:{}", classId);
        //发送管理员邮件
        try {
            String adminEmail = PropertiesUtil.getProperty("admin.email");
            MailUtil.SendNotifyMail(adminEmail, "活动修改信息接口: " + usermail + "-" + classId + " ");
        } catch (Exception e) {
            log.info("发送邮件异常", e);
        }
        return ServerResponse.createBySuccess();
    }


    //    18年年会拔河活动-（nsi-log表）
    @Override
    public ServerResponse TugOfWar_Insert(String nickname, String portrait, String openid, String number, String camp) {

        Log log_check = logMapper.selectByIndex05("年会拔河活动", openid);
        if (log_check != null) {
            System.out.println("插入-重复");
            return ServerResponse.createBySuccessMessage("插入重复-信息已存在");
        }
        Log log = new Log();
        log.setSign("年会拔河活动");
        log.setIndex02(new Date());
        log.setIndex03(nickname);
        log.setIndex04(portrait);
        log.setIndex05(openid);
        log.setIndex06(number);
        log.setIndex07(camp);
        int i = logMapper.insert(log);
        if (i > 0) {
            return ServerResponse.createBySuccessMessage("插入成功");
        } else {
            return ServerResponse.createByErrorMessage("插入失败");
        }
    }


    @Override
    public ServerResponse TugOfWar_update(String openid, String number) {

        int i = logMapper.updateByIndex05("年会拔河活动", openid, number);
        if (i > 0) {
            return ServerResponse.createBySuccessMessage("插入成功");
        } else {
            return ServerResponse.createByErrorMessage("插入失败");
        }
    }


    @Override
    public ServerResponse TugOfWar_MyNumber(String openid) {

        Log log = logMapper.selectByIndex05("年会拔河活动", openid);
        return ServerResponse.createBySuccess("查询成功", log);
    }

    @Override
    public ServerResponse TugOfWar_Camp(String camp) {

        List<Log> list = logMapper.selectByIndex07("年会拔河活动", camp);
        int count = 0;
        for (int i = 0; i < list.size(); i++) {
            count = count + Integer.valueOf(list.get(i).getIndex06());
        }
        return ServerResponse.createBySuccess("查询成功", count);
    }

    @Override
    public ServerResponse TugOfWar_Count() {

        List<Log> list_red = logMapper.selectByIndex07("年会拔河活动", "红");
        List<Log> list_blue = logMapper.selectByIndex07("年会拔河活动", "蓝");
        int count_red = 0;
        int count_blue = 0;
        for (int i = 0; i < list_red.size(); i++) {
            count_red = count_red + Integer.valueOf(list_red.get(i).getIndex06());
        }
        for (int i = 0; i < list_blue.size(); i++) {
            count_blue = count_blue + Integer.valueOf(list_blue.get(i).getIndex06());
        }
        Map<String, Integer> map = new HashMap<String, Integer>();
        map.put("red", count_red);
        map.put("blue", count_blue);

        return ServerResponse.createBySuccess("返回成功", map);
    }


    @Override
    public ServerResponse TugOfWar_PeopleList(String camp) {

        List<Log> list = logMapper.selectByIndex07("年会拔河活动", camp);

        return ServerResponse.createBySuccess("查询成功", list);
    }


    @Override
    public ServerResponse TugOfWar_AllPeopleList() {

        List<Log> list = logMapper.selectByIndex07All("年会拔河活动");

        return ServerResponse.createBySuccess("查询成功", list);
    }

    @Override
    public ServerResponse TugOfWar_Delete(int id) {
        int i = logMapper.deleteById(id);
        if (i != 1) {
            return ServerResponse.createByErrorMessage("操作失败");
        }
        return ServerResponse.createBySuccessMessage("操作成功");
    }


    // vis2019
    @Override
    public ServerResponse vis_insert(Vis2019 vis2019) {
        int i = vis2019Mapper.insert(vis2019);
        if (i > 0) {
            return ServerResponse.createBySuccess("添加成功", vis2019.getId());

        } else {
            return ServerResponse.createByErrorCodeMessage(0, "插入失败");
        }
    }

    @Override
    public ServerResponse vis_list(String type, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Vis2019> list = vis2019Mapper.selectByType(type);
        PageInfo pageInfo = new PageInfo(list);
        return ServerResponse.createBySuccess("返回成功", pageInfo);
    }

    @Override
    public ServerResponse vis_detail(int id) {
        Vis2019 vis2019 = vis2019Mapper.selectByPrimaryKey(id);
        return ServerResponse.createBySuccess("返回成功", vis2019);
    }


    @Override
    public ServerResponse vis_list_byPhone(String phone) {
        // 返回购买票种详情
        List<ActiveOrderVo> orderList = vis2019Mapper.vis_list_byPhone(phone);
        // 遍历状态和状态信息
        orderList.stream().forEach(vo -> vo.setStatusDesc(Const.OrderStatusEnum.codeOf(vo.getStatus()).getValue()));

        // 返回增票种详情
        List<ActiveOrderVo> entryList = entryAuditService.checkTicketApproved(phone);
        // 合并List
        orderList.addAll(entryList);
        System.out.println(JSON.toJSONString(orderList, true));
        // 去重并根据条件过略

        return ServerResponse.createBySuccess("返回成功", orderList);
    }


    @Override
    public ServerResponse vis_orderList(String type, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<ActiveReviewVo> list = vis2019Mapper.vis_orderList(type);
        PageInfo pageInfo = new PageInfo(list);
        return ServerResponse.createBySuccess("返回成功", pageInfo);
    }

    @Override
    public ServerResponse activityCheckInfo(int collectId) {
        EventCollect eventInfo = eventCollectService.selectById(collectId);
        if (eventInfo == null) {
            return ServerResponse.createByErrorMessage("门票失效,请联系管理人员!");
        }
        return ServerResponse.createBySuccess("查询成功!", eventInfo);
    }

    @Override
    public ServerResponse activityCheckIn(int collectId) {
        EventCollect eventCollect = new EventCollect();
        eventCollect.setId(collectId);
        eventCollect.setCheckIn(Const.CheckStatusEnum.SIGN_IN.getCode());

        eventCollectService.updateById(eventCollect);
        return ServerResponse.createBySuccessMessage("签到成功!");
    }


    @Override
    public ServerResponse activityCheckList(String searchKey, Integer acticeId, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<EventOrderVo> eventOrderVos = eventCollectService.findByActiveIdOrEventCollectAndOrder(acticeId, searchKey);
        for (EventOrderVo eventOrderVo : eventOrderVos) {
            eventOrderVo.setCheckInDesc(Const.CheckStatusEnum.codeOf(eventOrderVo.getCheckIn()).getValue());
        }
        PageInfo pageInfo = new PageInfo(eventOrderVos);
        return ServerResponse.createBySuccess("返回成功", pageInfo);
    }


    @Override
    public ServerResponse getImageSynthesis(String qrImgUrl, String username, String type) {
        if (StringUtils.isBlank(qrImgUrl)
                || StringUtils.isBlank(type)) {
            return ServerResponse.createByErrorMessage("参数不合法！");
        }
        // 查询电子门票地址
        ElectronicTicket ticket = electronicTicketService.selectOne(new EntityWrapper<ElectronicTicket>()
                .eq("type", type));
        if (ticket == null) {
            return ServerResponse.createByErrorMessage("该电子门票不存在！");
        }

        // 获取图片流
        BufferedImage bufferedImage = CompositeImageUtil.compositeImage(ticket.getImgUrl(), qrImgUrl);
        if (StringUtils.isNotBlank(username)) {
            bufferedImage = CompositeImageUtil.compositeText(bufferedImage, username);
        }

        // 生成图片地址
        String fileName = System.currentTimeMillis() + ".jpg";
        String filePath = PropertiesUtil.getProperty("compound.file.url") + fileName;
        // 生成文件
        CompositeImageUtil.writeImage(filePath, bufferedImage);
        // 返回服务器文件地址
        filePath = PropertiesUtil.getProperty("ticket.file.url") + fileName;
        log.info("【图片合成】地址：{}", filePath);
        return ServerResponse.createBySuccess(filePath);
    }

    @Override
    public ServerResponse getCheckStatistics(Integer activityId) {
        Map<String, Integer> resultMap = new HashMap<>();
        int payMentNum = eventCollectService.findByActivePayListCount(activityId);
        int checkNum = eventCollectService.findByActiveCheckInCount(activityId);
        resultMap.put("payMentNum", payMentNum);
        resultMap.put("checkNum", checkNum);
        return ServerResponse.createBySuccess(resultMap);
    }

    @Override
    public ServerResponse getCheckFeedBackGuestStatistics(Integer[] activeId) {
        Map<String, Integer> resultMap = new HashMap<>();
        String[] keys = {"feedBackCount", "guestCount"};
        String[] values = {"feedCheckCount", "guestCheckCount"};
        int checkNum = 0;
        int resultCount = 0;
        for (int i = 0; i < activeId.length; i++) {
            resultCount = eventCollectService.selectCount(new EntityWrapper<EventCollect>()
                    .eq("active_id", activeId[i])
                    .eq("verify", Const.HIDE_STATUS));
            checkNum = eventCollectService.findByActiveCheckInCount(activeId[i]);
            resultMap.put(keys[i], resultCount);
            resultMap.put(values[i], checkNum);
        }
        return ServerResponse.createBySuccess(resultMap);
    }


}
